import _ from 'lodash';
import axios from 'axios';
import router from '@/router';
import store from '@/store/modules/app/state'

const instance = axios.create({
  baseURL: process.env.NODE_ENV=="production"?"http://175.27.244.35:2012/api":"http://localhost:2012/api"
})

instance.interceptors.request.use(config => {
  if(_.endsWith( config.url, "/oauth/token")){
    config.headers['Authorization'] = "Basic Y2xpZW50SWQ6Y2xpZW50U2VjcmV0";
    config.headers['Content-Type'] = "application/x-www-form-urlencoded";
  }
  const accessToken = _.get(store, 'state.app.access_token') || sessionStorage.getItem("dev:access_token")
  if (accessToken) {
    config.headers['Authorization'] = 'Bearer ' + accessToken;
  }
  if(_.endsWith(config.url, '/logout')){
    window.sessionStorage.removeItem('dev:access_token')
  }
  store.isHasLogin = "";
  return config
})

instance.interceptors.response.use(response => response, error => {
  const status = _.get(error, 'response.status', 0)
  const errorResponse = _.get(error, 'response.data', {})
  const { code, detail, message } = errorResponse
  console.log(errorResponse, _.startsWith(errorResponse.error_description,"用户已登陆，不能重复登陆"));
  if(errorResponse.error=="unauthorized" && (_.startsWith(errorResponse.error_description,"用户已登陆，不能重复登陆"))) {
    store.isHasLogin = errorResponse.error_description;
    // new Error("用户已登陆，不能重复登陆.");
    return ;
  }else{
    switch (status) {
      case 504:
        throw new Error('网络异常')
      default:
        throw new Error(errorResponse.error_description || errorResponse);
    }
    if (code) {
      throw new Error(`[${code}] ${detail || message || error.message}`)
    } else {
      throw new Error(detail || message || error.message)
    }
  }
  
})

export default instance
